/**
 * 中间件集合
 */

/**
 * 延迟中间件 - 模拟网络延迟
 */
const delayMiddleware = (min = 100, max = 400) => {
  return (req, res, next) => {
    const delay = Math.random() * (max - min) + min
    setTimeout(next, delay)
  }
}

/**
 * 请求日志中间件
 */
const requestLogger = (req, res, next) => {
  const start = Date.now()
  const { method, url, ip } = req

  console.log(`📡 ${method} ${url} - ${ip}`)

  res.on('finish', () => {
    const duration = Date.now() - start
    const { statusCode } = res
    const statusEmoji = statusCode >= 400 ? '❌' : statusCode >= 300 ? '⚠️' : '✅'

    console.log(`${statusEmoji} ${method} ${url} - ${statusCode} - ${duration}ms`)
  })

  next()
}

/**
 * 错误处理中间件
 */
const errorHandler = (error, req, res, next) => {
  console.error('💥 Error:', error)

  // 如果响应已经发送，交给默认错误处理器
  if (res.headersSent) {
    return next(error)
  }

  // 根据错误类型返回不同的状态码
  let statusCode = 500
  let message = 'Internal Server Error'

  if (error.name === 'ValidationError') {
    statusCode = 400
    message = 'Validation Error'
  } else if (error.name === 'UnauthorizedError') {
    statusCode = 401
    message = 'Unauthorized'
  } else if (error.name === 'NotFoundError') {
    statusCode = 404
    message = 'Not Found'
  }

  res.status(statusCode).json({
    code: statusCode,
    message,
    data: null,
    error: process.env.NODE_ENV === 'development' ? error.message : undefined,
    stack: process.env.NODE_ENV === 'development' ? error.stack : undefined,
  })
}

/**
 * 404 处理中间件
 */
const notFoundHandler = (req, res) => {
  res.status(404).json({
    code: 404,
    message: 'Route not found',
    data: null,
    path: req.path,
    method: req.method,
  })
}

/**
 * 响应格式化中间件
 */
const responseFormatter = (req, res, next) => {
  // 保存原始的 json 方法
  const originalJson = res.json

  // 重写 json 方法
  res.json = function (data) {
    // 如果数据已经是标准格式，直接返回
    if (data && typeof data === 'object' && 'code' in data && 'message' in data) {
      return originalJson.call(this, data)
    }

    // 否则包装成标准格式
    const response = {
      code: res.statusCode || 200,
      message: res.statusCode >= 400 ? 'error' : 'success',
      data,
      timestamp: Date.now(),
    }

    return originalJson.call(this, response)
  }

  next()
}

/**
 * CORS 配置
 */
const corsOptions = {
  origin: function (origin, callback) {
    // 允许的域名列表
    const allowedOrigins = [
      'http://localhost:3000',
      'http://localhost:5173',
      'http://localhost:8000', // 添加前端开发服务器地址
      'http://127.0.0.1:3000',
      'http://127.0.0.1:5173',
      'http://127.0.0.1:8000',
    ]

    // 开发环境允许所有域名
    if (process.env.NODE_ENV === 'development' || !origin) {
      return callback(null, true)
    }

    if (allowedOrigins.includes(origin)) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  },
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
  allowedHeaders: [
    'Content-Type',
    'Authorization',
    'X-Requested-With',
    'X-Request-ID',
    'API-Version',
    'Accept',
    'Cache-Control',
    'Pragma',
  ],
  exposedHeaders: ['X-Request-ID', 'X-Response-Time', 'X-Total-Count'],
  credentials: true,
  maxAge: 86400, // 24小时预检缓存
}

// 导入验证中间件
const {
  validatePaginationParams,
  validateSearchParams,
  parseSortParams,
  parseFilterParams,
  validateListParams,
  validateSearchListParams,
} = require('./validation')

module.exports = {
  delayMiddleware,
  requestLogger,
  errorHandler,
  notFoundHandler,
  responseFormatter,
  corsOptions,
  validatePaginationParams,
  validateSearchParams,
  parseSortParams,
  parseFilterParams,
  validateListParams,
  validateSearchListParams,
}
